<?php

class RegisterForm extends CFormModel
{
	public $username;
	public $password;
	public $passwordRepeat;
	public $firstPet;

	public static $firstPets=array(
		110101=>'卡西',
	);

	public function rules()
	{
		return array(
			array('username,password,passwordRepeat,firstPet','required'),
			array('password','compare','compareAttribute'=>'passwordRepeat'),
			array('firstPet','in','range'=>array_keys(self::$firstPets), 'allowEmpty'=>false),
		);
	}

	public function attributeLabels()
	{
		return array(
			'username'=>'用户名',
			'password'=>'密码',
			'passwordRepeat'=>'密码确认',
			'firstPet'=>'初始宠物',
		);
	}
}

class RegisterAction extends CAction
{
	private $_form;
	private $_user;
	private $_pet;

	private function createUser()
	{
		$this->_user=new User;
		$this->_user->scenario='register';
		$this->_user->name=$this->_form->username;
		$this->_user->password=$this->_form->password;
		try {
			return User::saveUser($this->_user);
		}
		catch(CDbException $e){
			if(strstr($e->getMessage(),'1062 Duplicate entry')===false){
				throw $e;
			}

			$this->_form->addError($this->_form->username,'用户名已存在');
			return false;
		}
	}

	private function renderView()
	{
		$this->getController()->render('Register',
			array(
				'form'=>$this->_form,
				'firstPets'=>RegisterForm::$firstPets
			)
		);
	}

    public function run()
    {
		$this->_form=new RegisterForm;
		if(!isset($_POST['RegisterForm'])){
			$this->renderView();
			return;
		}

		$this->_form->attributes=$_POST['RegisterForm'];
		if(!$this->_form->validate()){
			$this->renderView();
			return;
		}

		if(!$this->createUser()){
			$this->renderView();
            return;
		}

		try {
			$this->_user->addPet(PetCategory::loadPetCategory($this->_form->firstPet)->createPet(),true);
		}
		catch(Exception $e){
			User::deleteUser($this->_user);
			throw $e;
		}

		$identity=new CUserIdentity($this->_user->name,$this->_user->password);
		Yii::app()->user->login($identity);
        $this->controller->redirect(
            array(
                'goto', 
                'id'=>Location::$default,
            )
        );
    }
}

?>
